import React from 'react';
import {ActionSheetIOS, Platform, Share,} from 'react-native';
import topView from 'rn-topview';
import ActionSheetAndroid from './ActionSheetAndroid';

const onAnimationEnd = (visible) => {
  if (!visible) {
    topView.remove();
  }
};

let instance = null;

export default {
  showActionSheetWithOptions(
    config, callback
  ) {
    if (Platform.OS === 'ios') {
      ActionSheetIOS.showActionSheetWithOptions(config, callback);
    } else {
      topView.set(
        <ActionSheetAndroid
          visible
          ref={ref => {
            instance = ref
          }}
          onAnimationEnd={onAnimationEnd}
          config={config}
          callback={callback}
        />
      )
    }
  },
  showShareActionSheetWithOptions(config, failureCallback, successCallback) {
    const content = {};
    const options = {};
    content.message = config.message;
    if (config.title) {
      content.title = config.title;
      options.dialogTitle = config.title;
    }
    if (config.url) {
      content.url = config.url;
    }
    if (config.excludedActivityTypes) {
      options.excludedActivityTypes = config.excludedActivityTypes;
    }
    if (config.tintColor) {
      options.tintColor = config.tintColor;
    }

    Share.share(content, options).then(result => {
      if (result.action === Share.sharedAction) {
        if (successCallback) {
          successCallback(true, result.activityType);
        } else if (result.action === Share.dismissedAction) {
          if (successCallback) {
            successCallback(false);
          }
        }
      }
    }).catch(error=>{
      if (failureCallback) {
        failureCallback(error);
      }
    });
  },

  close(){
    if (instance) {
      instance.close();
    }
  },
};